package com.biscuit.page.basicservice.service.api.impl;

import com.biscuit.page.basicservice.model.entities.mongo.BaseEntity;
import com.biscuit.page.basicservice.service.api.MongoService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author mazihao
 * @createTime 2024/4/13 13:45
 */
@Service
public class MongoServiceImpl implements MongoService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public <T extends BaseEntity> boolean isExist(Class<T> clazz) {
        return this.mongoTemplate.collectionExists(clazz);
    }

    @Override
    public <T extends BaseEntity> void create(Class<T> clazz) {
        this.mongoTemplate.createCollection(clazz);
    }

    @Override
    public <T extends BaseEntity> void drop(Class<T> clazz) {
        this.mongoTemplate.dropCollection(clazz);
    }

    @Override
    public <T extends BaseEntity> void clear(Class<T> clazz) {
        this.drop(clazz);
        this.create(clazz);
    }

    @Override
    public <T extends BaseEntity> List<T> list(Class<T> clazz) {
        return this.mongoTemplate.findAll(clazz);
    }

    @Override
    public <T extends BaseEntity> T insert(T data) {
        return this.mongoTemplate.insert(data);
    }

    @Override
    public <T extends BaseEntity> List<T> insertBatch(List<T> dataList) {
        return this.mongoTemplate.insert(dataList);
    }

    @Override
    public <T extends BaseEntity> void updateById(T data) {
        this.mongoTemplate.save(data);
    }

    @Override
    public <T extends BaseEntity> T getById(Class<T> clazz, String id) {
        return this.mongoTemplate.findById(id, clazz);
    }

    @Override
    public <T extends BaseEntity> void deleteById(Class<T> clazz, String id) {
        Query query = new Query(Criteria.where("id").is(id));
        this.mongoTemplate.remove(query, clazz);
    }

    @Override
    public <T extends BaseEntity> void deleteByIdList(Class<T> clazz, List<String> idList) {
        Query query = new Query(Criteria.where("id").in(idList));
        this.mongoTemplate.remove(query, clazz);
    }

}
